/*
 * 登录用户
 */
import _ from "lodash";
import { defineStore } from "pinia";
import localKey from "@/constants/local-storage-key-const";
import { HOME_PAGE_NAME } from "@/constants/system/home-const";
import { MENU_TYPE_ENUM } from "@/constants/system/menu-const";
import { getTokenFromCookie } from "@/utils/cookie-util";
import { localClear, localRead, localSave } from "@/utils/local-util";

export const useUserStore = defineStore({
  id: "userStore",
  state: () => ({
    //左侧菜单树形结构
    menuTree: [] as any,
    //存在页面路由的菜单集合
    menuRouterList: [],
    //是否完成menuRouter初始化
    menuRouterInitFlag: false,
    //父类菜单集合
    menuParentIdListMap: new Map(),
    // 功能点集合
    pointsList: [],
    // 标签页
    tagNav: [] as any,
    // 缓存
    keepAliveIncludes: [] as any,
    menuList: [],
    userInfo: {
      token: "",
      //员工id
      employeeId: "",
      //登录名
      loginName: "",
      //姓名
      actualName: "",
      //手机号
      phone: "",
      //部门id
      departmentId: "",
      //部门名词
      departmentName: "",
      //是否为超级管理员
      administratorFlag: true,
      //上次登录ip
      lastLoginIp: "",
      //上次登录 设备
      lastLoginUserAgent: "",
      //上次登录时间
      lastLoginTime: "",
    },
  }),
  getters: {
    getToken(state) {
      if (state.userInfo.token) {
        return state.userInfo.token;
      }
      return getTokenFromCookie();
    },
    //是否初始化了 路由
    getMenuRouterInitFlag(state) {
      return state.menuRouterInitFlag;
    },
    //菜单树
    getMenuTree(state) {
      return state.menuTree;
    },
    //菜单的路由
    getMenuRouterList(state) {
      return state.menuRouterList;
    },
    //菜单的父级id
    getMenuParentIdListMap(state) {
      return state.menuParentIdListMap;
    },
    //功能点
    getPointList(state) {
      if (_.isEmpty(state.pointsList)) {
        let localUserPoints = localRead(localKey.USER_POINTS) || "";
        state.pointsList = localUserPoints ? JSON.parse(localUserPoints) : [];
      }
      return state.pointsList;
    },
    //标签页
    getTagNav(state) {
      if (_.isNull(state.tagNav)) {
        let localTagNav = localRead(localKey.USER_TAG_NAV) || "";
        state.tagNav = localTagNav ? JSON.parse(localTagNav) : [];
      }
      let tagNavList = _.cloneDeep(state.tagNav) || [];
      // @ts-ignore
      tagNavList.unshift({
        menuName: HOME_PAGE_NAME,
        menuTitle: "首页",
      });
      return tagNavList;
    },
  },

  actions: {
    logout() {
      this.menuList = [];
      this.tagNav = [];
      this.userInfo = {
        token: "",
        //员工id
        employeeId: "",
        //登录名
        loginName: "",
        //姓名
        actualName: "",
        //手机号
        phone: "",
        //部门id
        departmentId: "",
        //部门名词
        departmentName: "",
        //是否为超级管理员
        administratorFlag: true,
        //上次登录ip
        lastLoginIp: "",
        //上次登录 设备
        lastLoginUserAgent: "",
        //上次登录时间
        lastLoginTime: "",
      };
      localClear();
    },
    //设置登录信息
    setUserLoginInfo(data: any) {
      // 用户基本信息
      this.userInfo = data;
      //菜单权限
      this.menuTree = buildMenuTree(data.menuList);

      //拥有路由的菜单
      this.menuRouterList = data.menuList.filter((e:any) => e.path || e.frameUrl);

      //父级菜单集合
      this.menuParentIdListMap = buildMenuParentIdListMap(this.menuTree);
      console.log(this.menuParentIdListMap);

      //功能点
      this.pointsList = data.menuList.filter(
        (menu: any) =>
          menu.menuType === MENU_TYPE_ENUM.POINTS.value &&
          menu.visibleFlag &&
          !menu.disabledFlag
      );
    },
    setToken(token: string) {
      this.userInfo.token = token;
    },
    //设置标签页
    setTagNav(route: any, from: any) {
      if (_.isNull(this.tagNav)) {
        let localTagNav = localRead(localKey.USER_TAG_NAV) || "";
        this.tagNav = localTagNav ? JSON.parse(localTagNav) : [];
      }
      // name唯一标识
      let name = route.name;
      if (!name || name == HOME_PAGE_NAME || name === "403" || name === "404") {
        return;
      }
      let findTag = (this.tagNav || []).find((e: any) => e.menuName == name);
      if (findTag) {
        // @ts-ignore
        findTag.fromMenuName = from.name;
        // @ts-ignore
        findTag.fromMenuQuery = from.query;
      } else {
        // @ts-ignore
        this.tagNav.push({
          // @ts-ignore
          menuName: name,
          // @ts-ignore
          menuTitle: route.meta.title,
          menuQuery: route.query,
          // @ts-ignore
          fromMenuName: from.name,
          fromMenuQuery: from.query,
        });
      }
      localSave(localKey.USER_TAG_NAV, JSON.stringify(this.tagNav));
    },
    //关闭标签页
    closeTagNav(menuName: any, closeAll: any) {
      if (_.isEmpty(this.getTagNav)) return;
      if (closeAll && !menuName) {
        this.tagNav = [];
        this.clearKeepAliveIncludes();
      } else {
        let findIndex = (this.tagNav || []).findIndex(
          (e:any) => e.menuName == menuName
        );
        if (closeAll) {
          if (findIndex == -1) {
            this.tagNav = [];
            this.clearKeepAliveIncludes();
          } else {
            let tagNavElement = (this.tagNav || [])[findIndex] as any;
            this.tagNav = [tagNavElement];
            this.clearKeepAliveIncludes(tagNavElement.menuName);
          }
        } else {
          (this.tagNav || []).splice(findIndex, 1);
          this.deleteKeepAliveIncludes(menuName);
        }
      }
      localSave(localKey.USER_TAG_NAV, JSON.stringify(this.tagNav));
    },
    //关闭页面
    closePage(route: any, router: any, path: any) {
      if (!this.getTagNav || _.isEmpty(this.getTagNav)) return;
      if (path) {
        router.push({ path });
      } else {
        // 寻找tagNav
        let index = this.getTagNav.findIndex((e:any) => e.menuName == route.name);
        if (index == -1) {
          router.push({ name: HOME_PAGE_NAME });
        } else {
          let tagNav = this.getTagNav[index];
          if (
            tagNav.fromMenuName &&
            this.getTagNav.some((e:any) => e.menuName == tagNav.fromMenuName)
          ) {
            router.push({
              name: tagNav.fromMenuName,
              query: tagNav.fromMenuQuery,
            });
          } else {
            // 查询左侧tag
            let leftTagNav = this.getTagNav[index - 1];
            router.push({
              name: leftTagNav.menuName,
              query: leftTagNav.menuQuery,
            });
          }
        }
      }
      this.closeTagNav(route.name, false);
    },
    // 加入缓存
    pushKeepAliveIncludes(val: any) {
      if (!val) {
        return;
      }
      if (!this.keepAliveIncludes) {
        this.keepAliveIncludes = [];
      }
      if (this.keepAliveIncludes.length < 30) {
        let number = this.keepAliveIncludes.findIndex((e:any) => e === val);
        if (number === -1) {
          this.keepAliveIncludes.push(val);
        }
      }
    },
    // 删除缓存
    deleteKeepAliveIncludes(val: any) {
      if (!this.keepAliveIncludes || !val) {
        return;
      }
      let number = this.keepAliveIncludes.findIndex((e:any) => e === val);
      if (number !== -1) {
        this.keepAliveIncludes.splice(number, 1);
      }
    },
    // 清空缓存
    clearKeepAliveIncludes(val?: any) {
      if (!val) {
        this.keepAliveIncludes = [];
        return;
      }
      if (!this.keepAliveIncludes?.includes(val)) {
        this.keepAliveIncludes = [];
        return;
      }
      this.keepAliveIncludes = [val];
    },
  },
  persist: true,
});

/**
 * 构建菜单父级集合
 */
// 递归构建菜单父级ID列表映射
function buildMenuParentIdListMap(menuTree: any) {
  // 创建一个Map对象，用于存储菜单父级ID列表
  let menuParentIdListMap = new Map();
  // 调用递归函数，构建菜单父级ID列表映射
  recursiveBuildMenuParentIdListMap(menuTree, [], menuParentIdListMap);
  // 返回菜单父级ID列表映射
  return menuParentIdListMap;
}

// 递归构建菜单父级ID列表映射
function recursiveBuildMenuParentIdListMap(
  menuList: any, // 菜单列表
  parentMenuList: any, // 父级菜单列表
  menuParentIdListMap: any // 菜单父级ID列表映射
) {
  for (const e of menuList) {
    // 遍历菜单列表中的每个菜单项
    // 顶级parentMenuList清空
    if (e.parentId == 0) {
      // 如果当前菜单项是顶级菜单，则清空父级菜单列表
      parentMenuList = [];
    }
    let menuIdStr = e.menuId.toString(); // 将菜单ID转换为字符串
    let cloneParentMenuList = _.cloneDeep(parentMenuList); // 深拷贝父级菜单列表
    if (!_.isEmpty(e.children) && e.menuName) {
      // 如果当前菜单项有子菜单且菜单名称不为空
      // 递归
      cloneParentMenuList.push({ name: menuIdStr, title: e.menuName }); // 将当前菜单项添加到克隆的父级菜单列表中
      recursiveBuildMenuParentIdListMap(
        e.children, // 递归调用，处理子菜单
        cloneParentMenuList, // 传递克隆的父级菜单列表
        menuParentIdListMap // 传递菜单父级ID列表映射
      );
    } else {
      // 如果当前菜单项没有子菜单
      menuParentIdListMap.set(menuIdStr, cloneParentMenuList); // 将菜单ID和对应的父级菜单列表映射存储到map中
    }
  }
}

/**
 * 构建菜单树
 *
 * @param  menuList
 * @returns
 */
function buildMenuTree(menuList: any) {
  //1 获取所有 有效的 目录和菜单
  let catalogAndMenuList = menuList.filter(
    (menu:any) =>
      menu.menuType !== MENU_TYPE_ENUM.POINTS.value &&
      menu.visibleFlag &&
      !menu.disabledFlag
  );

  //2 获取顶级目录
  let topCatalogList = catalogAndMenuList.filter((menu:any) => menu.parentId === 0);
  for (const topCatalog of topCatalogList) {
    buildMenuChildren(topCatalog, catalogAndMenuList);
  }
  return topCatalogList;
}

// 递归构建菜单子项
function buildMenuChildren(menu: any, allMenuList: any) {
  // 根据菜单id过滤出子菜单
  let children = allMenuList.filter((e: any) => e.parentId === menu.menuId);
  // 如果没有子菜单，则返回
  if (children.length === 0) {
    return;
  }
  // 将子菜单添加到当前菜单的children属性中
  menu.children = children;
  // 递归构建子菜单的子菜单
  for (const item of children) {
    buildMenuChildren(item, allMenuList);
  }
}
